# @Time    :2025/4/10    16:14
class Node(object):
    def __init__(self, elem):
        self.elem = elem
        self.lchild = None
        self.rchild = None


class Tree(object):
    """二叉树"""

    def __init__(self):
        self.root = None

    def add(self, elem):
        node = Node(elem)  # 构造一个节点
        if self.root is None:
            self.root = node
            return
        queue = [self.root]  # 将根节点添加到队列
        #  ---------树的插入操作
        while queue:
            cur_node = queue.pop(0)  # 当前处理的节点 ，从队尾拿出一个数据去读
            if cur_node.lchild is None:
                cur_node.lchild = node
                return
            else:
                queue.append(cur_node.lchild)
            if cur_node.rchild is None:
                cur_node.rchild = node
                return
            else:
                queue.append(cur_node.rchild)

    def breadth_travel(self):
        """广度遍历"""
        if self.root is None:
            return
        queue = [self.root]  # 将根节点添加到队列中
        while queue:  # 只有队列不为空就一直取下去
            cur_node = queue.pop(0)  # 从队列中取出一个节点
            print(cur_node.elem, end=" ")
            if cur_node.lchild is not None:
                queue.append(cur_node.lchild)
            if cur_node.rchild is not None:
                queue.append(cur_node.rchild)

    def preorder(self, node):  # 把根节点传入进来
        """先序遍历 根左右"""
        if node is None:
            return
        print(node.elem, end=" ")  # 打印传进来 根节点的数据
        self.preorder(node.lchild)  # 左子树
        self.preorder(node.rchild)  # 右子树
    def inorder(self, node):  # 把根节点传入进来
        """中序遍历 左根右"""
        if node is None:
            return
        self.inorder(node.lchild)  # 左子树
        print(node.elem, end=" ")  # 打印传进来 根节点的数据
        self.inorder(node.rchild)  # 右子树

    def postrder(self, node):  # 把根节点传入进来
        """后序遍历 左右根"""
        if node is None:
            return
        self.postrder(node.lchild)  # 左子树
        self.postrder(node.rchild)  # 右子树
        print(node.elem, end=" ")  # 打印传进来 根节点的数据


if __name__ == "__main__":
    tree = Tree()
    tree.add(0)
    tree.add(1)
    tree.add(2)
    tree.add(3)
    tree.add(4)
    tree.add(5)
    tree.add(6)
    tree.add(7)
    tree.add(8)
    tree.add(9)
    tree.breadth_travel()
    print("广度 ")
    tree.preorder(tree.root)
    print("先序 ")
    tree.inorder(tree.root)
    print("中序 ")
    tree.postrder(tree.root)
    print("后序 ")
